package com.example.community.interceptor;

import com.example.community.dao.pojo.LoginTicket;
import com.example.community.dao.pojo.User;
import com.example.community.service.LoginTicketService;
import com.example.community.service.UserService;
import com.example.community.uitls.CookieUtil;
import com.example.community.uitls.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.Authenticator;
import java.util.Date;

/**
 * @ClassName: LoginInterceptor
 * @Description:
 * @Author
 * @Date 2022-03-18
 * @Version 1.0
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    LoginTicketService loginTicketService;

    @Autowired
    UserService userService;

    @Autowired
    HostHolder hostHolder;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从cookie中或缺凭证
        String ticket = CookieUtil.getValue(request,"ticket");
        if (ticket!=null){
            //查询凭证
            LoginTicket loginTicket = loginTicketService.findLoginTicket(ticket);
            //检查凭证是否有效
            if ( loginTicket.getStatus() == 0 && loginTicket!=null && loginTicket.getExpired().after(new Date())){
                //根据id获取用户并把它存起来，后面在模板解析时可以用
                User user = userService.findUserById(loginTicket.getUserId());
                hostHolder.setUser(user);
                //构建用户认证的结果，并存入到SecurityContext，以便于Security进行授权
                Authentication authentication = new UsernamePasswordAuthenticationToken(
                        user,user.getPassword(),userService.getAuthorities(user.getId()));
                SecurityContextHolder.setContext(new SecurityContextImpl(authentication));
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //获取线程中的user，模板解析时用
        User user = hostHolder.getUser();
        if (user!=null && modelAndView != null){
            modelAndView.addObject("loginUser",user);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.clear();
//        SecurityContextHolder.clearContext();
    }
}
